package com.syqc.comlib.custom

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import androidx.appcompat.app.AlertDialog
import com.syqc.comlib.R
import com.syqc.comlib.databinding.DialogInfoBinding
import java.lang.ref.WeakReference

/**
 *@Author pc_hfjs
 *@Date 2022/5/17 9:53
 *@Desc
 */
object MPrivacyDialog {
    private var infoDialog: AlertDialog? = null
    private var reference: WeakReference<Context?>? = null
    @SuppressLint("StaticFieldLeak")
    private var binding: DialogInfoBinding? = null

    private fun initDialog(activity: Context, message: String, callback: View.OnClickListener) {
        val builder = AlertDialog.Builder(activity, R.style.GspTheme_Dialog)
        binding = DialogInfoBinding.inflate(LayoutInflater.from(activity))
        builder.setView(binding!!.root)
        binding!!.tvMessage.text = message
        builder.setCancelable(false)
        binding!!.tvCancel.setOnClickListener {
            callback.onClick(it)
            clear()
        }
        binding!!.tvToOpen.setOnClickListener {
            callback.onClick(it)
            clear()
        }
        infoDialog = builder.create()
    }


    private fun init(activity: Context, message: String, callback: View.OnClickListener) {
        if (infoDialog == null || reference == null || reference!!.get() == null) {
            reference = WeakReference(activity)
            initDialog(activity, message, callback)
        } else {
            binding!!.tvMessage.text = message
        }
    }


    fun showDialog(activity: Activity, message: String, callback: View.OnClickListener):MPrivacyDialog {
        if (infoDialog != null && infoDialog!!.isShowing) return this
        init(activity, message, callback)
        if (!activity.isFinishing) infoDialog?.show()
        return this
    }

    /**
     * 关闭dialog
     */
    private fun dismissDialog() {
        infoDialog?.let {
            if (it.isShowing) it.dismiss()
        }
    }

    /**
     * 清除Dialog
     */
    fun clear() {
        binding=null
        dismissDialog()
        infoDialog = null
        reference?.clear()
        reference = null
    }

}